
var TabInit = {
    soulSort: false,
    method: "POST",
    toolbar: "#toolbarDemo",
    defaultToolbar: [{
        title: '刷新' //标题
        ,layEvent: 'LAYTABLE_FLUSH' //事件名，用于 toolbar 事件中使用
        ,icon: 'layui-icon-refresh-1' //图标类名
    },'filter', 'print', 'exports'],
    overflow: {
        type: 'tips'
        ,hoverTime: 500
        ,color: '#fff'
        ,bgColor: '#393d49'
    },
    request: {pageName: 'page',limitName: 'pagesize'},
    response: {statusCode: 2000},
    filter: {
        items:['column','data','condition','editCondition','excel','clearCache'],
        cache: true,
        clearFilter: true
    },
    text: {
        none: '<div><div><img style="width:70px;" src="/static/admin/images/welnodata.png" /></div><span>暂无数据</span></div>'
    }
};

var list_bill_cols_str = {field:'status',title:'审核状态',width:120,templet: function(d){
        if(d.billid > 0){
            if(d.status == 0){
                return '<div style="text-align: center"><span class="list_billid billstrlan" onclick="openPage(stuff_ru.php'+d.id+');">审批中</span></div>'
            }else if(d.status == 1){
                return '<div style="text-align: center"><span class="list_billid billstrlv" onclick="openPage(\'show.php?id='+d.id+'\');">审批通过</span></div>'
            }else{
                return '';
            }
        }
        return '<div style="text-align: center"><span class="list_billid billstrshoudong" onclick="openPage(stuff_ru.php'+d.id+');">直接新建</span></div>';
    }};

function get_table_contextmenu(soulTable){
    return {
        header: [{
            name: '复制',
            icon: 'layui-icon layui-icon-template',
            click: function(obj) {
                soulTable.copy(obj.text)
                layer.msg('复制成功！')

            }
        }],
            body: [{name: '复制',icon: 'layui-icon layui-icon-template', click: function(obj) {
                soulTable.copy(obj.text)
                layer.msg('复制成功！')
            }
        }],
    }
}

$(document).ready(function () {
    // 存储刷新后的信息
    window.addEventListener('beforeunload',function () {
        if(localStorage.getItem('top_yi_menu_info')){
            localStorage.setItem('top_yi_menu_info',localStorage.getItem('top_yi_menu_info'));
        }
        if(localStorage.getItem('active_yi_menu')){
            localStorage.setItem('active_yi_menu',localStorage.getItem('active_yi_menu'));
        }
        if(localStorage.getItem('active_er_menu')){
            localStorage.setItem('active_er_menu',localStorage.getItem('active_er_menu'));
        }
        if(localStorage.getItem('active_san_menu')){
            localStorage.setItem('active_san_menu',localStorage.getItem('active_san_menu'));
        }
    });

    // 时间选择
    $('.bdate_sea_y').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy',//显示格式
        startView: '4',
        type: "datetimerange",
        minView: "4",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',dataPickerAfterSea);

    $('.bdate_sea_ym').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm',//显示格式
        startView: '3',
        type: "datetimerange",
        minView: "3",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',dataPickerAfterSea);

    $('.bdate_sea_ymd').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd',//显示格式
        minView: "month",//设置只显示到月份
        type: "datetimerange",
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true,//显示今日按钮
    }).on('changeDate',dataPickerAfterSea);

    $('.bdate_sea_ymdhi').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd hh:ii',//显示格式
        type: "datetimerange",
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',dataPickerAfterSea);

    layui.use(['laydate','layer'],function(){
        var laydate = layui.laydate;

        lay('.bdate_sea_range_y').each(function(){
            laydate.render({
                elem: this
                ,type: 'year'
                ,range: true
                ,done: function(value, date, endDate){
                    var thisObj = $(this)[0].elem;
                    setTimeout(function () {
                        dataLayerAfterSea(thisObj);
                    },200)
                }
            });
        });
        lay('.bdate_sea_one_ym').each(function(){
            laydate.render({
                elem: this
                ,type: 'month'
                ,done: function(value, date, endDate){
                    var thisObj = $(this)[0].elem;
                    setTimeout(function () {
                        dataLayerAfterSea(thisObj);
                    },200)
                }
            });
        });
        lay('.bdate_sea_range_ym').each(function(){
            laydate.render({
                elem: this
                ,type: 'month'
                ,range: true
                ,done: function(value, date, endDate){
                    var thisObj = $(this)[0].elem;
                    setTimeout(function () {
                        dataLayerAfterSea(thisObj);
                    },200)
                }
            });
        });
        lay('.bdate_sea_range_ymd').each(function(){
            laydate.render({
                elem: this
                ,trigger: 'click'
                ,type: 'date'
                ,range: true
                ,done: function(value, date, endDate){
                    var thisObj = $(this)[0].elem;
                    setTimeout(function () {
                        dataLayerAfterSea(thisObj);
                    },200)
                }
            });
        });
        lay('.bdate_sea_range_ymdhi').each(function(){
            laydate.render({
                elem: this
                ,trigger: 'click'
                ,type: 'datetime'
                ,range: true
                ,done: function(value, date, endDate){
                    var thisObj = $(this)[0].elem;
                    setTimeout(function () {
                        dataLayerAfterSea(thisObj);
                    },200)
                }
            });
        });
    });

    layui.use(['laytp','tree','table','form','soulTable'], function () {
        var table = layui.table;
        table.on('toolbar(datalist)', function(obj){
            switch(obj.event){
                case 'LAYTABLE_FLUSH':
                    window.location.reload();
                    break;
            }
        });
    });


    //动态添加table初始化组件
    $("#tab-init-tool-but").html(
        '<li class="layui-nav-item">\n' +
        '                    <button class="layui-btn layui-btn-primar" id="refresh_table" title="刷新">\n' +
        '                        <i class="layui-icon layui-icon-refresh-1"></i>\n' +
        '                    </button>\n' +
        '                </li>\n' +
        '                <li class="layui-nav-item layui-form">\n' +
        '                    <button class="layui-btn layui-btn-primary" id="export_table" onclick="exportTable(this)" title="导出">\n' +
        '                        <i class="layui-icon layui-icon-export"></i>\n' +
        '                    </button>\n' +
        '                </li>\n' +
        '                <li class="layui-nav-item layui-form">\n' +
        '                    <button class="layui-btn layui-btn-primary" id="cols_table" title="筛选列">\n' +
        '                        <i class="layui-icon layui-icon-cols"></i>\n' +
        '                    </button>\n' +
        '                </li>\n' +
        '                <li class="layui-nav-item">\n' +
        '                    <button class="layui-btn layui-btn-primary" id="search_table" title="查询">\n' +
        '                        <i class="layui-icon layui-icon-search"></i>\n' +
        '                    </button>\n' +
        '                </li>'
    );
    //table刷新
    $('#refresh_table').click(function () {
        window.location.reload();
    });

    // $('#export_table').click(function () {
    //     var thatObj = $(this);
    //     layui.use(['dropdown','soulTable'],function() {
    //         var soulTable = layui.soulTable;
    //
    //         console.log(soulTable.config);
    //
    //         var dropdown = layui.dropdown;
    //         dropdown.render({
    //             elem: thatObj
    //             ,show: true
    //             ,align: 'right'
    //             ,data: [
    //                 {id: 'xuan',templet: '导出选中'}
    //                 ,{id: 'curr',templet: '导出当前页'}
    //                 ,{id: 'all',templet: '导出全部'}
    //             ],click: function(obj){
    //                 var tabid = 'datalist'
    //
    //                 var tabtitle = '导出信息AAA';
    //                 if(obj.id == 'xuan'){
    //                     soulTable.export(tabid, {filename: tabtitle+'.xlsx',checked: true});
    //                 }
    //                 if(obj.id == 'curr'){
    //                     soulTable.export(tabid, {filename: tabtitle+'.xlsx',curPage: true});
    //                 }
    //                 if(obj.id == 'all'){
    //                     soulTable.export(tabid, {filename: tabtitle+'.xlsx'});
    //                 }
    //             }
    //         });
    //     });
    //
    //     // setTimeout(function () {
    //     //     $( 'div[lay-event="LAYTABLE_EXPORT"]').click();
    //     // })
    // });
    // 筛选列
    $('#cols_table').click(function () {
        var left = $(this).offset().left + 'px';
        setTimeout(function () {
            $( 'div[lay-event="LAYTABLE_COLS"]').click();
            $('.layui-table-tool').css({'left':left,'z-index':'99'});
        })
    });
    // 数据table选中变色
    $(".laytp-container").on('click', '.layui-table-body tr ', function () {
        var data_index = $(this).attr('data-index');//得到当前的tr的index
        $(".layui-table-body tr").removeClass('table-click-color');
        $(".layui-table-body tr[data-index=" + data_index + "]").addClass('table-click-color')//改变当前tr颜色
    });
    // 操作按钮点击变色
    $('#table_list').on('click','.bar_opt',function () {
        $('#table_list .bar_opt').each(function () {
            $(this).css('color','#2272eb');
        });
        $(this).css('color','#1ca5ff');
    });
    // 列表页打开搜索信息
    $('#search_table').click(function () {
        if($('#search-form').is(':hidden')){
            $('#search-form').show();
        }else{
            $('#search-form').hide();
        }
    });

})

function setSouTableExport(title, type=1, url='') {
    setTimeout(function () {
        $("#datalist").attr('custit', title)
    },500)
    // $("#export_table").attr('onclick',"exportTable(this, '"+title+"', "+type+", '"+url+"')");
}
function exportTable(Obj, title, type, url=''){
    if(type == 1){
        layui.use(['dropdown','soulTable'],function() {
            var soulTable = layui.soulTable;
            var dropdown = layui.dropdown;

            dropdown.render({
                elem: Obj
                ,show: true
                ,align: 'right'
                ,data: [
                    {id: 'xuan',templet: '导出选中'}
                    ,{id: 'curr',templet: '导出当前页'}
                    ,{id: 'all',templet: '导出全部'}
                ],click: function(obj){
                    var tabid = 'datalist';
                    var tabtitle = title || '导出信息';
                    if(obj.id == 'xuan'){
                        soulTable.export(tabid, {filename: tabtitle+'.xlsx',checked: true});
                    }
                    if(obj.id == 'curr'){
                        soulTable.export(tabid, {filename: tabtitle+'.xlsx',curPage: true});
                    }
                    if(obj.id == 'all'){
                        soulTable.export(tabid, {filename: tabtitle+'.xlsx'});
                    }
                }
            });
        });
    }else if(type == 2){
        setTimeout(function () {
            $( 'div[lay-event="LAYTABLE_EXPORT"]').click();
        })
    }else{
        console.log('后端导出');
        console.log(url);
    }
}

function listTableReset(){
    $("#TableSearchFormId")[0].reset();
    $("#TableSearchFormId select option").removeAttr("selected");
    render_from();
}

function listTableSearch(form, table){
    form.on('select',function (data) {
        searchTableFunc(form, table)
    });
    $("#TableSearchButton").on('click', function(){
        searchTableFunc(form, table)
    });
}
function keyTableSearch() {
    if (event.keyCode == 13) {
        layui.use(['form', 'table'], function () {
            searchTableFunc(layui.form, layui.table)
        });
    }
}
function searchTableFunc(form, table) {
    setTimeout(function () {
        var data = form.val('TableSearchForm');
        var TableConfig = table.getOptions('datalist');
        if(TableConfig && TableConfig.where){
            for (key in TableConfig.where){
                if(!data.hasOwnProperty(key)){
                    data[key] =  TableConfig.where[key];
                }
            }
        }
        table.reload('datalist', {
            page:{curr:1},
            where: data
        });
    },1);
}

function tbaleFilterRowDouble(table, $filter, callback) {
    table.on('rowDouble('+$filter+')', function (obj) {
        if(callback){
            callback(obj, obj.data, $(obj.tr).data('index'));
        }
    });
}

function dataPickerAfterSea(dx) {
    if($(dx.currentTarget).parents("#TableSearchFormId").length > 0){
        layui.use(['form', 'table'], function () {
            searchTableFunc(layui.form, layui.table)
        });
    }
    return;
}
function dataLayerAfterSea(obj) {
    if($(obj).parents("#TableSearchFormId").length > 0){
        layui.use(['form', 'table'], function () {
            searchTableFunc(layui.form, layui.table)
        });
    }
    return;
}

function tableButShow(menubutArr){
    var topOutStr = '', topInStr = '', topInStrnei='';

    for (var key in menubutArr) {
        if(menubutArr[key].pagetype === 0 || menubutArr[key].pagetype === 2){
            // if(menubutArr[key].postype == 1){
            //     topOutStr += '<li class="layui-nav-item" onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')">';
            //     topOutStr += '<button class="layui-btn layui-btn-primary outbut">';
            //     topOutStr += '<i class="layui-icon layui-icon-add-1"></i>';
            //     topOutStr += menubutArr[key].title;
            //     topOutStr += '</button>';
            //     topOutStr += '</li>';
            // }else{
            //     if(menubutArr[key].postype == 2){
            //         topInStrnei += '<dd>';
            //         topInStrnei += '<a href="javascript:;" onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')">';
            //         topInStrnei += menubutArr[key].title;
            //         topInStrnei += '</a>';
            //         topInStrnei += '</dd>';
            //     }
            // }

            if(menubutArr[key].butname == 'add' || menubutArr[key].butname == 'add_flow' || menubutArr[key].butname == 'addjia' || menubutArr[key].butname == 'muladd'){
                topOutStr += '<button class = "layui-btn layui-btn-sm laytp-container-tool-button zong_button" ' +
                    'onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')" style="padding-right: 12px;">' +
                    '<i class="layui-icon layui-icon-add-1"></i>'+menubutArr[key].title+'</button>';
            }else if(menubutArr[key].butname == 'import'){
                topOutStr += '<button class = "layui-btn layui-btn-sm laytp-container-tool-button zong_button" ' +
                    'onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')" style="padding-right: 12px;">' +
                    '<i class="layui-icon layui-icon-add-1"></i>'+menubutArr[key].title+'</button>';
            }else{
                if(menubutArr[key].isxuan == 1){
                    topOutStr += '<button class = "layui-btn layui-btn-sm laytp-container-tool-button xuan_button" ' +
                        'onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')" style="padding-right: 12px;">' +
                        '<i class="layui-icon layui-icon-ok-circle"></i>'+menubutArr[key].title+'</button>';
                }else if(menubutArr[key].isxuan == 2){
                    topOutStr += '<button class = "layui-btn layui-btn-sm laytp-container-tool-button xuan_button" ' +
                        'onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')" style="padding-right: 12px;">' +
                        '<i class="layui-icon layui-icon-search"></i>'+menubutArr[key].title+'</button>';
                }else{
                    topOutStr += '<button class = "layui-btn layui-btn-sm laytp-container-tool-button zong_button" ' +
                        'onclick="auth_but_func_'+menubutArr[key].butname+'(\''+menubutArr[key].title+'\')">'+menubutArr[key].title+'</button>';
                }
            }

        }
    }
    $('.layui-btn-container').html(topOutStr);


    // if(topInStrnei){
    //     topInStr += '<li class="layui-nav-item">';
    //     topInStr += '<button class="layui-btn layui-btn-primary" id="opt_menu">';
    //     topInStr += '<i class="layui-icon layui-icon-triangle-d"></i>操作';
    //     topInStr += '</button>';
    //     topInStr += '<dl class="layui-nav-child" id="opt_dl">';
    //     topInStr += topInStrnei;
    //     topInStr += '</dl>';
    //     topInStr += '</li>';
    // }

    // $("#tab-init-auth-but-out").html(topOutStr);
    // $("#tab-init-auth-but-in").html(topInStr);
    // curTopDropBut()
}

function curTopDropBut() {
    var btn = document.getElementById('opt_menu');
    var box = document.getElementById('opt_dl');
    var timer = null;
    if(box){
        box.onmouseover = btn.onmouseover = function(){
            if(timer) clearTimeout(timer)
            $("#opt_dl").show();
        }
        box.onmouseout = btn.onmouseout = function(){
            timer = setTimeout(function(){
                $("#opt_dl").hide();
            },200);
        }
    }
}

function get_table_check_idarr(datalist='datalist') {
    var checkStatus = layui.table.checkStatus(datalist).data;
    var ids = [];
    for(var i=0;i<checkStatus.length;i++){
        ids.push(checkStatus[i].id)
    }
    return ids;
}



function show_tab_but(currTabData){
    layui.use(['dropdown'], function () {
        var dropdown = layui.dropdown;

        $.each(currTabData, function(cura,item){
            var autDiv = $('tr[data-index=' + item.LAY_TABLE_INDEX + '] .tab-list-authbut');
            $($(autDiv[0]).find('.bar_opt')[0]).removeClass('layui-hide');
            $($(autDiv[0]).find('.bar_opt')[1]).removeClass('layui-hide');
            $($(autDiv[0]).find('.bar_opt')[2]).removeClass('layui-hide');
            $($(autDiv[1]).find('.bar_opt')[0]).removeClass('layui-hide');
            $($(autDiv[1]).find('.bar_opt')[1]).removeClass('layui-hide');
            $($(autDiv[1]).find('.bar_opt')[2]).removeClass('layui-hide');

            if($(autDiv[0]).find('.bar_opt').length > 3){
                var authbut = [];
                $.each($(autDiv[0]).find('.bar_opt'), function(index,item){
                    if(index >=3){
                        authbut.push({title: $(item).data('title'), id: $(item).data('butname')})
                    }
                });
                currTabData[cura].authbut = authbut;
                $('tr[data-index=' + item.LAY_TABLE_INDEX + '] .tab-list-authbut').append(' <a href="javascript:;" class="bar_opt" onclick="show_tab_drop(this, '+cura+')">更多<i class="layui-icon layui-icon-triangle-d"></i></a>');
            }
        });
        dropdown.render();
    });
}
function show_tab_drop(obj, index){
    layui.use(['dropdown'], function () {
        var dropdown = layui.dropdown;

        dropdown.render({
            elem: obj
            ,show: true //外部事件触发即显示
            ,data: currTabData[index].authbut
            ,click: function(data, othis){
                if (typeof(window['auth_but_func_'+data.id]) != "undefined"){
                    window['auth_but_func_'+data.id](data.title, index);
                }
            }
            ,align: 'right'
            ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);'
        });
    });
}


function toggle_search() {
    if($('#search-form .search_hide').is(':hidden')){
        $('#search-form .search_hide').show();
        $('#search-form #search_open').html('<i class="layui-icon layui-icon-up"></i>收起');
    }else{
        $('#search-form .search_hide').hide();
        $('#search-form #search_open').html('<i class="layui-icon layui-icon-down"></i>展开');
    }
}


// 处理多页面点击空白处关闭菜单并处理样式
// $(document).bind('click', function(e) {
//     var e = e || window.event;
//     var elem = e.target || e.srcElement;
//     while (elem) {
//         if ($(e.target).parents('#sideMenu').length != 0) {
//             return;
//         }
//         elem = elem.parentNode;
//     }
//     parent.colseSideStyle();
// });

